/**
 * @FileName: OrderController.java
 * @Author
 * @Description:
 * @Date 2016年4月20日 下午5:12:13
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.controller.h5;

import java.util.Date;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.constant.H5ApiConstant;
import cn.hpclub.server.model.ActivityOrder;
import cn.hpclub.server.model.Business;
import cn.hpclub.server.model.BusinessOrder;
import cn.hpclub.server.model.MemberOrg;
import cn.hpclub.server.model.Organization;
import cn.hpclub.server.util.DateKit;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.OrderType;

/**
 * 营销活动、资费办理的订单提交。之前由DPR调用。 目前状态为2017 01 13之后没人调用，DPR->DZG切换时丢失了。后续可以加起来。
 */
public class OrderController extends BaseH5Controller implements H5ApiConstant{

    public static final String MODULE_ID     = "moduleId";
    public static final String TARIFF_CODE   = "business_code";
    public static final String TARIFF_NAME   = "business_name";
    public static final String TYPE_ID   = "type_id";
    public static final String CLIENT_MOBILE = "phone_no";
    public static final String ORDER_AMOUNT  = "amount";
    public static final String USER_ID       = "userid";

    public static final String ORDER_ID      = "order_id";
    public static final String USER_NAME     = "user_name";
    public static final String USER_MOBILE   = "user_mobile";
    public static final String ORG_ID        = "org_id";
    public static final String ORG_NAME      = "org_name";
    public static final String PACKAGE_NAME  = "package_name";

    public static final String CREATE_TIME   = "create_time";
    public static final String REMARK        = "remark";

    private static Logger      log           = LoggerFactory.getLogger(OrderController.class);

    @Before(value = { POST.class, Tx.class })
    // @ActionKey("submit")
    public void submit(){
        JSONObject result = setResponseObj(H5ApiConstant.ResultCode.FAIL_CODE, H5ApiConstant.Msg.PARA_ILLEGAL, null);
        try{
            String tariffCode = getPara(TARIFF_CODE);
            String clientMobile = getPara(CLIENT_MOBILE);
            String module = getPara(MODULE_ID);
            String user = getPara(USER_ID);
            String orderAmount = getPara(ORDER_AMOUNT);
            String businessName = getPara(TARIFF_NAME);
            String typeId = getPara(TYPE_ID);
            boolean legal = checkData(tariffCode, clientMobile, user, module, orderAmount);
            if(!legal){
                result = setResponseObj(H5ApiConstant.ResultCode.FAIL_CODE, H5ApiConstant.Msg.PARA_ILLEGAL, null);
                log.error("userId:" + user + "，tariffCode:" + tariffCode + "，clientMobile:" + clientMobile
                        + ",moduleId:" + module + ",payAmount:" + orderAmount);
                renderText(result.toString());
                return;
            }

            int moduleId = Integer.valueOf(module);
            if(StrKit.isBlank(module) && StrKit.notBlank(typeId)){
                if("2".equals(typeId) || "3".equals(typeId)){
                    moduleId = Constant.ModuleID.YINGXIAO;
                }else{
                    moduleId = Constant.ModuleID.ZIFEI;
                }
            }


            int userId = Integer.valueOf(user);
            double payAmount = Double.valueOf(orderAmount);

            JSONObject orderOut = null;
            if(moduleId == Constant.ModuleID.ZIFEI){
                BusinessOrder order = saveBusinessOrder(tariffCode, clientMobile, userId, payAmount,businessName);
                orderOut = buildBusinessReturnOrder(order);
            } else{
                ActivityOrder order = saveActivityOrder(tariffCode, clientMobile, userId, payAmount,businessName);
                orderOut = buildActivityReturnOrder(order);
            }
            // return order
            result = setResponseObj(H5ApiConstant.ResultCode.SUCCESS_CODE, H5ApiConstant.Msg.SUCCESS, orderOut);
            renderText(result.toString());

        }
        catch(Exception e){
            result = setResponseObj(H5ApiConstant.ResultCode.EXCEPTION_CODE, H5ApiConstant.Msg.EXCEPTION, null);
            e.printStackTrace();
            renderText(result.toString());
        }

    }

    /**
     * @Title: buildBusinessReturnOrder
     * @Description:TODO void
     */

    private JSONObject buildBusinessReturnOrder(BusinessOrder order){
        JSONObject obj = new JSONObject();
        obj.put(ORDER_ID, order.getStr(BusinessOrder.ORDER_ID));
        obj.put(USER_ID, order.getInt(BusinessOrder.USER_ID));
        obj.put(USER_NAME, order.getStr(BusinessOrder.USER_NAME));
        obj.put(USER_MOBILE, order.getStr(BusinessOrder.USER_MOBILE));
        obj.put(ORG_ID, order.getInt(BusinessOrder.ORG_ID));
        obj.put(ORG_NAME, order.getStr(BusinessOrder.ORG_NAME));
        obj.put(CLIENT_MOBILE, order.getStr(BusinessOrder.CLIENT_MOBILE));

        obj.put(TARIFF_CODE, order.getStr(BusinessOrder.TARIFF_CODE));
        obj.put(PACKAGE_NAME, order.getStr(BusinessOrder.PACKAGE_NAME));

        obj.put(ORDER_AMOUNT, order.getDouble(BusinessOrder.ORDER_AMOUNT));
        obj.put(CREATE_TIME, DateKit.toStr(order.getDate(BusinessOrder.CREATE_TIME), "yyyy-MM-dd HH:mm:ss"));
        obj.put(REMARK, order.getStr(BusinessOrder.REMARK));

        return obj;
    }

    private JSONObject buildActivityReturnOrder(ActivityOrder order){
        JSONObject obj = new JSONObject();
        obj.put(ORDER_ID, order.getStr(BusinessOrder.ORDER_ID));
        obj.put(USER_ID, order.getInt(BusinessOrder.USER_ID));
        obj.put(USER_NAME, order.getStr(BusinessOrder.USER_NAME));
        obj.put(USER_MOBILE, order.getStr(BusinessOrder.USER_MOBILE));
        obj.put(ORG_ID, order.getInt(BusinessOrder.ORG_ID));
        obj.put(ORG_NAME, order.getStr(BusinessOrder.ORG_NAME));
        obj.put(CLIENT_MOBILE, order.getStr(BusinessOrder.CLIENT_MOBILE));

        obj.put(TARIFF_CODE, order.getStr(BusinessOrder.TARIFF_CODE));
        obj.put(PACKAGE_NAME, order.getStr(BusinessOrder.PACKAGE_NAME));

        obj.put(ORDER_AMOUNT, order.getDouble(BusinessOrder.ORDER_AMOUNT));
        obj.put(CREATE_TIME, DateKit.toStr(order.getDate(BusinessOrder.CREATE_TIME), "yyyy-MM-dd HH:mm:ss"));
        obj.put(REMARK, order.getStr(BusinessOrder.REMARK));
        return obj;
    }

    /**
     * @Title: saveBusinessOrder
     * @Description:TODO
     * @param tariffCode
     * @param clientMobile
     * @param userId
     * @param payAmount
     *            void
     */

    private BusinessOrder saveBusinessOrder(String tariffCode, String clientMobile, int userId, double payAmount,String businessName)
            throws Exception{
        BusinessOrder order = new BusinessOrder();
        order.set(BusinessOrder.USER_ID, userId);
        order.set(BusinessOrder.ORDER_ID, generateBusinessOrderId(userId));
        MemberOrg member = MemberOrg.dao.getActiveMemberbyUserId(userId);
        if(member != null){
            order.set(BusinessOrder.USER_NAME, getAttrString(member.getStr(MemberOrg.NAME)));
            order.set(BusinessOrder.USER_MOBILE, getAttrString(member.getStr(MemberOrg.USER_NAME)));
            order.set(BusinessOrder.CLIENT_MOBILE, clientMobile);
            order.set(BusinessOrder.TARIFF_CODE, tariffCode);
            //String businessName = Business.dao.getName(tariffCode);
            order.set(BusinessOrder.PACKAGE_NAME, businessName);
            order.set(BusinessOrder.ORDER_AMOUNT, payAmount);
            order.set(BusinessOrder.CREATE_TIME, new Date());

            // order.set(BusinessOrder.PAY_STATUS, 1);
            // order.set(BusinessOrder.PAY_AMOUNT, );
            // order.set(BusinessOrder.PAY_TIME, );
            // order.set(BusinessOrder.PAY_PLAT, );

            Integer orgId = member.getInt(MemberOrg.ORG_ID);
            order.set(BusinessOrder.ORG_ID, orgId);
            order.set(BusinessOrder.ORG_NAME, Organization.dao.getOrgNameByOrgId(orgId));
            order.set(BusinessOrder.REMARK, "".equalsIgnoreCase(businessName) ? "套餐不存在或已停用" : "");
        } else{
            // 对于不存在的userid和资费代码，因为boss系统可以照办，所以，暂时还是先将order记录存下来。移到我们的系统，包括支付，那么userid不存在的情况下，是不能提单的。TODO
            order.set(BusinessOrder.USER_NAME, "用户不存在或已禁用");
            order.set(BusinessOrder.USER_MOBILE, "");
            order.set(BusinessOrder.CLIENT_MOBILE, clientMobile);
            order.set(BusinessOrder.TARIFF_CODE, tariffCode);
            order.set(BusinessOrder.PACKAGE_NAME, "");
            order.set(BusinessOrder.ORDER_AMOUNT, payAmount);
            order.set(BusinessOrder.CREATE_TIME, new Date());

            // order.set(BusinessOrder.PAY_STATUS, 1);
            // order.set(BusinessOrder.PAY_AMOUNT, );
            // order.set(BusinessOrder.PAY_TIME, );
            // order.set(BusinessOrder.PAY_PLAT, );

            order.set(BusinessOrder.ORG_ID, 0);
            order.set(BusinessOrder.ORG_NAME, "用户不存在或已禁用");
            order.set(BusinessOrder.REMARK, "用户不存在或已禁用");
        }

        order.save();
        return order;
    }

    private ActivityOrder saveActivityOrder(String tariffCode, String clientMobile, int userId, double payAmount,String businessName)
            throws Exception{
        ActivityOrder order = new ActivityOrder();
        order.set(BusinessOrder.USER_ID, userId);
        order.set(BusinessOrder.ORDER_ID, generateActivityOrderId(userId));
        MemberOrg member = MemberOrg.dao.getActiveMemberbyUserId(userId);
        if(member != null){
            order.set(BusinessOrder.USER_NAME, getAttrString(member.getStr(MemberOrg.NAME)));
            order.set(BusinessOrder.USER_MOBILE, getAttrString(member.getStr(MemberOrg.USER_NAME)));
            order.set(BusinessOrder.CLIENT_MOBILE, clientMobile);
            order.set(BusinessOrder.TARIFF_CODE, tariffCode);
            //String businessName = Business.dao.getName(tariffCode);
            order.set(BusinessOrder.PACKAGE_NAME, businessName);
            order.set(BusinessOrder.ORDER_AMOUNT, payAmount);
            order.set(BusinessOrder.CREATE_TIME, new Date());

            // order.set(BusinessOrder.PAY_STATUS, 1);
            // order.set(BusinessOrder.PAY_AMOUNT, );
            // order.set(BusinessOrder.PAY_TIME, );
            // order.set(BusinessOrder.PAY_PLAT, );

            Integer orgId = member.getInt(MemberOrg.ORG_ID);
            order.set(BusinessOrder.ORG_ID, orgId);
            order.set(BusinessOrder.ORG_NAME, Organization.dao.getOrgNameByOrgId(orgId));
            order.set(BusinessOrder.REMARK, "".equalsIgnoreCase(businessName) ? "套餐不存在或已停用" : "");
        } else{
            // 对于不存在的userid和资费代码，因为boss系统可以照办，所以，暂时还是先将order记录存下来。移到我们的系统，包括支付，那么userid不存在的情况下，是不能提单的。TODO
            order.set(BusinessOrder.USER_NAME, "用户不存在或已禁用");
            order.set(BusinessOrder.USER_MOBILE, "");
            order.set(BusinessOrder.CLIENT_MOBILE, clientMobile);
            order.set(BusinessOrder.TARIFF_CODE, tariffCode);
            order.set(BusinessOrder.PACKAGE_NAME, "");
            order.set(BusinessOrder.ORDER_AMOUNT, payAmount);
            order.set(BusinessOrder.CREATE_TIME, new Date());

            // order.set(BusinessOrder.PAY_STATUS, 1);
            // order.set(BusinessOrder.PAY_AMOUNT, );
            // order.set(BusinessOrder.PAY_TIME, );
            // order.set(BusinessOrder.PAY_PLAT, );

            order.set(BusinessOrder.ORG_ID, 0);
            order.set(BusinessOrder.ORG_NAME, "用户不存在或已禁用");
            order.set(BusinessOrder.REMARK, "用户不存在或已禁用");
        }

        order.save();
        return order;
    }

    private String getAttrString(String strAttr){
        if(strAttr == null){
            return "";
        }
        return strAttr;
    }

    /**
     * @Title: checkData
     * @Description:TODO
     * @param
     */

    private boolean checkData(String tariffCode, String clientMobile, String userId, String moduleId, String payAmount)
            throws Exception{
        if(StrKit.isBlank(tariffCode) || StrKit.isBlank(clientMobile) || (!isModuleIdValid(moduleId))
                || StrKit.isBlank(payAmount) || StrKit.isBlank(userId)){
            return false;
        }

        // 对于不存在的userid和资费代码，因为boss系统可以照办，所以，暂时还是先将order记录存下来。移到我们的系统，包括支付，那么userid不存在的情况下，是不能提单的。TODO
        if(!MemberOrg.dao.exist(Integer.valueOf(userId))){
            log.warn("submit order,but userid " + userId + " does not exist");
            // return false;
        }
        if(!Business.dao.exist(tariffCode)){
            log.warn("submit order,but businesscode " + tariffCode + " does not exist");
            // return false;
        }

        return true;
    }

    private boolean isModuleIdValid(String moduleId){
        if(moduleId == null){
            return false;
        }
        int id = Integer.valueOf(moduleId);
        if(id == Constant.ModuleID.ZIFEI){
            return true;
        } else if(id == Constant.ModuleID.YINGXIAO){
            return true;
        }
        log.error("submit order,module id illegal:" + moduleId);
        return false;

    }

    private String generateBusinessOrderId(int userId){
        String dateStr = DateKit.toStr(new Date(), "yyMMdd");
        System.out.println("dateStr:" + dateStr);
        MemberOrg memberInfo = MemberOrg.dao.getMemberOrgInfoByUserId(userId);
        String cityCode = null;
        String groupId = null;
        boolean userExist = MemberOrg.dao.exist(userId);
        if((!userExist) || (memberInfo == null)){
            cityCode = "00"; // TODO
            groupId = "E" + userId;
        } else{
            cityCode = "" + memberInfo.getInt("region_id");
            groupId = MemberOrg.dao.getOrgNumCodebyUserid(userId);
        }
        return OrderType.BUSINESS.getName() + dateStr + InterfaceUtil.getOrderSeq(OrderType.BUSINESS) + cityCode
                + groupId; // TODO
    }

    /**
     * @Title: generateActivityOrderId
     * @Description:生成订单号。如果userid在我们的系统里面不存在，则在订单号里面加userid，避免重复。 一旦支付由我们自己做，
     *                                                             则，
     *                                                             不再允许userid不存在的订单
     *                                                             。
     *                                                             套餐不存在的orderid是正常拼接的
     *                                                             ，因为不需要资费代码参数
     * @param userId
     * @return String
     */
    private String generateActivityOrderId(int userId){
        String dateStr = DateKit.toStr(new Date(), "yyMMdd");
        System.out.println("dateStr:" + dateStr);
        MemberOrg memberInfo = MemberOrg.dao.getMemberOrgInfoByUserId(userId);
        String cityCode = null;
        String groupId = null;
        boolean userExist = MemberOrg.dao.exist(userId);
        if((!userExist) || (memberInfo == null)){
            cityCode = "00"; // TODO
            groupId = "E" + userId; // TODO
        } else{
            cityCode = "" + memberInfo.getInt("region_id");
            groupId = MemberOrg.dao.getOrgNumCodebyUserid(userId);
        }
        return OrderType.ACTIVITY.getName() + dateStr + InterfaceUtil.getOrderSeq(OrderType.ACTIVITY) + cityCode
                + groupId;
    }

}
